#include "SDL.h"
#include "tetris.h"
#include "winInit.h"
#include "texture.h"
#include "render.h"
#include "drawblocks.h"
#include "SDL_mixer.h"
#include <stdio.h>

int main( int argc, char* args[] )
{
    TT_UNUSED(argc);
    TT_UNUSED(args);

    TT_Window win;
    if(initWindow(&win) == false){
        return -1;
    }
    TT_Texture backgroundImgTexture = loadImageTexture(&win, TT_IMG_PATH"background.png");
    TT_Texture gameoverImgTexture = loadImageTexture(&win, TT_IMG_PATH"game-over-red.jpg");

    TT_Texture greenBlockImgTexture = loadImageTexture(&win, TT_IMG_PATH"greenblock.png");
    TT_Texture redBlockImgTexture = loadImageTexture(&win, TT_IMG_PATH"redblock.png");
    TT_Texture blueBlockImgTexture = loadImageTexture(&win, TT_IMG_PATH"blueblock.png");
    TT_Texture yellowBlockImgTexture = loadImageTexture(&win, TT_IMG_PATH"yellowblock.png");

    TT_Texture blocksTexture[TT_BLOCK_COLOR_NUM] = {
        greenBlockImgTexture,
        redBlockImgTexture,
        blueBlockImgTexture,
        yellowBlockImgTexture
    };

    TTF_Font *font = TTF_OpenFont(TT_FONT_PATH"courbd.ttf", 22);
    SDL_Color fontColor = {245,245,245,0xff};

    Mix_Chunk *putSound = Mix_LoadWAV(TT_SOUND_PATH"high.wav");
    Mix_Chunk *moveSound = Mix_LoadWAV(TT_SOUND_PATH"low.wav");
    Mix_Chunk *transSound = Mix_LoadWAV(TT_SOUND_PATH"medium.wav");
    Mix_Chunk *gameoverSound = Mix_LoadWAV(TT_SOUND_PATH"gameover.wav");
    Mix_Chunk *startSound = Mix_LoadWAV(TT_SOUND_PATH"start.wav");
    Mix_Chunk *completeSound = Mix_LoadWAV(TT_SOUND_PATH"complete.wav");
    if(!putSound || !moveSound || !transSound || !gameoverSound || !startSound || !completeSound){
        SDL_Log("load wav error: %s\n", Mix_GetError());
    }

    TT_Block block;
    initBlocks(&block, blocksTexture, TT_BLOCK_GREEN, TT_WallsBuff, 2, 200, 100);
    updateWalls(&block);
    block.putSound = putSound;
    block.moveSound = moveSound;
    block.transSound = transSound;
    block.startSound = startSound;
    block.completeSound = completeSound;

    char *scoreStr = SDL_malloc(64);
    char *maxScoreStr = SDL_malloc(64);
    Uint32 startTime = SDL_GetTicks();
    TT_Bool quit = false;
    SDL_Event e;
    int prepared = 0;
    while (!quit) {
        while (SDL_PollEvent(&e)) {
            if(e.type == SDL_QUIT){
                quit = true;
            }else {
                blocksHandle(&block, &e);
                prepared = 1;
            }
        }
        if (prepared) {
            moveBlocks(&block);
            prepared=0;
        }

        if((SDL_GetTicks() - startTime) >= 800){
            startTime = SDL_GetTicks();
            autoMoveDownBlocks(&block);
        }

        SDL_SetRenderDrawColor(win.render, 0xff, 0xff, 0xff, 0xff);
        SDL_RenderClear(win.render);

        renderImageFromTexture(&win, &backgroundImgTexture, NULL, 0, 0);
        drawBlocks(&win, &block);
        drawRemainBlocks(&win, &block);

        if(isBlockDead(&block) && !isGameOver(&block)){
            SDL_Log("Block Dead!\n\n");
            copyDeadBlocksToRemainBlocks(&block);
            deleteCompletedBlocks(&block);            
            if(isGameOver(&block)){
                SDL_Log("Game Over!\n\n");
                Mix_PlayChannel(-1, gameoverSound, 0);
            }else{
                if(block.putSound)
                    Mix_PlayChannel(-1, block.putSound, 0);
                SDL_Log("New block!\n\n");
                reInitBlocks(&block, 200, 100);
                updateWalls(&block);
            }            
        }
        if(isGameOver(&block)){
            renderImageFromTexture(&win, &gameoverImgTexture, NULL, TT_WINDOW_WIDTH/2 - gameoverImgTexture.width/2, TT_WINDOW_HEIGHT/2 - gameoverImgTexture.height/2);
        }
        sprintf(scoreStr, "score: %d", block.score);
        sprintf(maxScoreStr, "high score: %d", block.maxScore);
        renderText(&win, font, &fontColor, scoreStr, 3, 0);
        renderText(&win, font, &fontColor, maxScoreStr, 200, 0);
        drawNextBlocks(&win, &block, TT_NEXT_BLOCKS_X, TT_NEXT_BLOCKS_Y);
        renderText(&win, font, &fontColor, "Press 's' key to start game.", 25, 540);
        renderText(&win, font, &fontColor, "Press 'r' key to restart game.", 15, 580);
        renderText(&win, font, &fontColor, "Next block: ", 3, 35);

        SDL_RenderPresent(win.render);
        SDL_Delay(10);
    }

    freeTexture(&backgroundImgTexture);
    freeTexture(&gameoverImgTexture);
    for(int i = 0; i < TT_BLOCK_COLOR_NUM; i++){
        freeTexture(&blocksTexture[i]);
    }
    SDL_Quit();
    SDL_Log("SDL_Quit!\n");
    return 0;
}
